<template>
  <div class="call-record">
    <page-box>
      <template #top>
        <alert-msg
          content="系统产生的所有类型通话的记录，表头支持自定义配置，快捷查询最多支持10个条件，复杂搜索请使用高级搜索"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="quickSearchList" :form="quickForm" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="searchFun">查询</el-button>
        <advanced-search
          :searchType="isAdvanced"
          :fieldList="fieldList"
          :fieldSelectList="fieldSelectList"
          :customList="customList"
          :conditionList="conditionList"
          @onSaveCondition="saveConditionFun"
          @onSearchFun="handleSearch"
          @onDeleteCustomClick="deleteCustomClick"
          ref="customSearch"
        ></advanced-search>
      </template>
      <template #table>
        <resize-table
          ref="tableRef"
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          :showPagination="true"
          :headersConfig="true"
          @onCheckHeadersChange="checkHeadersChange"
          :batchs="batchs"
          @onBatchClick="batchClick"
          :dynamic="true"
          v-loading="loading"
        >
          <!-- 通话类型 -->
          <template #callType="{ scope }"
            ><span>{{ getCallTypeText(scope.row.callType) }}</span></template
          >
          <!-- 客户地区 -->
          <template #customerCountry="{ scope }"
            ><span>{{ getProvince(scope.row) }}</span></template
          >
          <!-- 客户振铃时长 -->
          <template #customerRingDuration="{ scope }"
            ><span>{{ getTimeLength(scope.row.customerRingDuration) }}</span></template
          >
          <!-- 通话时长 -->
          <template #bridgeDuration="{ scope }"
            ><span>{{ getTimeLength(scope.row.bridgeDuration) }}</span></template
          >
          <!-- 座席振铃时长 -->
          <template #agentRingDuration="{ scope }"
            ><span>{{ getTimeLength(scope.row.agentRingDuration) }}</span></template
          >
          <!-- 失败原因 -->
          <template #failureReason="{ scope }"
            ><span>{{ getFailureReason(scope.row.failureReason) }}</span></template
          >
          <!-- 满意度调查结果 -->
          <template #keys="{ scope }"
            ><satisfactions
              :callType="scope.row.callType"
              :satisfactionData="satisfactionData"
              :keys="scope.row.keys"
            ></satisfactions
          ></template>
          <!-- 满意度时长 -->
          <template #satisfyDuration="{ scope }"
            ><span>{{ getTimeLength(scope.row.satisfyDuration) }}</span></template
          >

          <!-- 挂机方 -->
          <template #hangUpSide="{ scope }"
            ><span>{{ getHangUpSideName(scope.row.hangUpSide) }}</span></template
          >
          <!-- 呼叫状态 -->
          <template #status="{ scope }"
            ><span>{{ getCallStatusName(scope.row.status) }}</span></template
          >
          <!-- 外显号地区 -->
          <template #displayNumberArea="{ scope }">
            <span v-show="scope.row.displayNumber">
              <!-- 有外显号，再匹配外显号地区 -->
              {{ scope.row.callerProvince }}-{{ scope.row.callerCity }}
            </span></template
          >
          <!-- 录音 -->
          <template #recordFileUrl="{ scope }">
            <span class="record-audio" v-if="scope.row.recordFileUrl">
              <audio-operate
                :row="{
                  url: scope.row.doubleTrackFileUrl || scope.row.recordFileUrl || scope.row.voiceMailUrl,
                  isplay: scope.row.isplay,
                  _id: scope.row._id
                }"
                @onAudioClick="restTablePlay"
              ></audio-operate>
              <a
                :href="scope.row.doubleTrackFileUrl || scope.row.recordFileUrl || scope.row.voiceMailUrl"
                target="_blank"
                download
              >
                <i class="MC_iconfont MC_icon-shangchuan-xiazai"></i>
              </a>
            </span>
          </template>
          <!-- 留言录音 -->
          <template #voiceMailUrl="{ scope }">
            <span class="record-audio" v-if="scope.row.voiceMailUrl">
              <audio-operate
                :row="{
                  url: scope.row.doubleTrackFileUrl || scope.row.voiceMailUrl,
                  isplay: scope.row.isplay,
                  _id: scope.row._id
                }"
                @onAudioClick="restTablePlay"
              ></audio-operate>
              <a :href="scope.row.doubleTrackFileUrl || scope.row.voiceMailUrl" target="_blank" download>
                <i class="MC_iconfont MC_icon-shangchuan-xiazai"></i>
              </a>
            </span>
          </template>
          <template #oprate="{ scope }">
            <el-button type="text" class="btn" @click="toDetail(scope.row)">详情</el-button>
          </template>
        </resize-table>
      </template>
    </page-box>
    <!-- 新建客户 -->
    <resize-drawer
      :title="drawer.title"
      :drawer="drawer.show"
      :size="960"
      :isShowMoreBtn="false"
      @onCloseDraw="closeDraw"
      @onCancelFun="closeDraw"
    >
      <template #column>
        <call-info @tabChange="tabChange" :scene="'callrecord'" :callId="drawer.callId"></call-info>
      </template>
    </resize-drawer>
  </div>
</template>

<script lang="ts">
import audioOperate from '@/common/components/audio/audio-operate.vue'
import { defineComponent, getCurrentInstance, nextTick, onMounted, reactive, toRefs, ref, markRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { batchDel, cusDetail, delCus, addCus, getHeader, updateHeader } from '@app/customer/apis/pool'
import {
  getCdrList,
  setCdrHeader,
  getCdrHeader,
  saveOrUpdateQuickQuery,
  getQuickQuery,
  deleteQuickQuery
} from '@app/base/apis/call'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import resizeDrawer from '@/common/components/resize-drawer/index.vue'
import pageBox from '@common/components/page-box.vue'
import advancedSearch from '@common/components/advanced-search/index.vue'
import { deepClone, getCallTimeLength } from '@/common/utils/common'
import { getData } from '@app/call-center/apis/caller-state'
import mcCache from '@/common/utils/mc-get-cache'
import alertMsg from '@common/components/alert/index.vue'
import satisfactions from '@/app/call-center/views/call-record/satisfactions.vue'
import bus from '@/common/utils/bus'
import { getCallStatusName } from '@app/customer/utils/common'
import { getCurrentDateTime, getFormatDateTime } from '@/common/utils/common'
// 右侧卡片
import callInfo from '@/app/call-center/views/recent-calls/component/cardInfo.vue'

import { userModule } from '@/common/store/modules/user'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  isAdvanced: boolean
  advancedObj: any
  fieldList: Record<string, unknown>[]
  satisfactionData: any
  quickForm: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  pagingData: Record<string, number>
  batchs: Record<string, unknown>[]
  drawer: Record<string, unknown>
  addForm: Record<string, unknown>
  detailData: Record<string, unknown>
  loading: boolean
}
export default defineComponent({
  name: 'customerPool',
  components: {
    searchForm,
    resizeTable,
    resizeDrawer,
    pageBox,
    advancedSearch,
    alertMsg,
    satisfactions,
    callInfo,
    audioOperate
  },
  setup() {
    const customSearch: any = ref(null)
    const instance: any = getCurrentInstance()
    const USERMODULE = userModule()
    const state: State = reactive({
      satisfactionData: {},
      loading: false,
      quickSearchList: [
        {
          name: '呼叫时间',
          field: 'startTime',
          type: 'datetime-range'
        },
        {
          name: '快捷检索',
          field: 'customerOrAgentName',
          type: 'text',
          placeholder: '客户号码或座席名称'
        }
      ],
      fieldList: [
        {
          name: '快捷检索',
          field: 'customerOrAgentName',
          type: 'text',
          placeholder: '客户号码或座席名称'
        },
        {
          name: '呼叫类型',
          field: 'callType',
          type: 'dropdown',
          choices: [{ label: '呼入', value: 'incoming' }]
        },
        {
          name: '呼叫时间',
          field: 'customerName',
          type: 'datetime-range'
        }
      ],
      quickForm: {
        startTime: [],
        customerOrAgentName: ''
      },
      tableHeaders: [
        {
          label: '通话记录ID',
          prop: '_id',
          show: true
        },
        {
          label: '呼叫类型',
          prop: 'callType',
          show: true,
          custom: true
        },
        {
          label: '呼叫时间',
          prop: 'startTime',
          show: true
        },
        {
          label: '客户号码',
          prop: 'customerNumber',
          show: true
        },
        {
          label: '通话录音',
          prop: 'recordFileUrl',
          show: true,
          custom: true,
          width: 120
        },
        {
          label: '服务组',
          prop: 'queueName',
          show: true
        },
        {
          label: '座席名称',
          prop: 'agentName',
          show: true
        },
        {
          label: '呼叫状态',
          prop: 'status',
          custom: true
        },
        {
          label: '通话时长', // 通话结束时间 - 呼叫时间
          prop: 'bridgeDuration',
          custom: true
        },
        {
          label: '留言录音',
          prop: 'voiceMailUrl'
        },
        {
          label: '客户地区',
          prop: 'customerCountry',
          custom: true
        },
        {
          label: '服务号',
          prop: 'trunkNumber'
        },
        {
          label: '外显号',
          prop: 'displayNumber'
        },
        {
          label: '外显号地区',
          prop: 'displayNumberArea',
          custom: true
        },
        {
          label: '虚拟号',
          prop: 'virtualNumber',
          show: false
        },
        {
          label: '座席工号',
          prop: 'agentNumber',
          show: false
        },
        {
          label: '语音导航',
          prop: 'ivrName',
          show: false
        },
        {
          label: '座席振铃时长', // 座席接听应答时间 - 呼叫时间
          prop: 'agentRingDuration',
          custom: true,
          sortable: true,
          show: false
        },
        {
          label: '座席接听时间', // 座席接听应答时间 - 呼叫时间
          prop: 'agentAnswerTime',
          sortable: true,
          show: false
        },
        {
          label: '呼叫座席时间', // 座席接听应答时间 - 呼叫时间
          prop: 'agentStartTime',
          sortable: true,
          show: false
        },
        {
          label: '客户振铃时长', // 客户接听应答时间 - 呼叫时间
          prop: 'customerRingDuration',
          custom: true,
          sortable: true,
          show: false
        },
        {
          label: '客户接听时间',
          prop: 'customerAnswerTime',
          show: false
        },
        {
          label: '挂机方',
          prop: 'hangUpSide',
          custom: true,
          show: false
        },
        {
          label: '呼叫失败原因',
          prop: 'failureReason',
          custom: true,
          show: false
        },
        {
          label: '满意度调查结果',
          prop: 'keys',
          custom: true,
          show: false
        },
        {
          label: '满意度调查时长', // 满意度结束时间 - 满意度开始时间
          prop: 'satisfyDuration',
          custom: true,
          show: false
        },
        {
          label: '客户名称',
          prop: 'customerName'
        },
        {
          label: '挂机时间',
          prop: 'hangupTime'
        },
        // {
        //   label: '标签',
        //   prop: 'tags'
        // },
        // {
        //   label: '座席部门',
        //   prop: 'department',
        //   show: false
        // },
        {
          label: '转出座席工号',
          prop: 'transferAgent',
          show: false
        },
        {
          label: '操作',
          prop: 'oprate',
          show: true
        }
      ],
      tableData: [],
      pagingData: {
        page: 1,
        total: 0,
        limit: 10
      },
      batchs: [
        {
          name: '导出记录',
          action: 'distribute',
          _id: 'customer_assign'
        },
        {
          name: '导出录音',
          action: 'delete',
          _id: 'customer_delete'
        },
        {
          name: '导出留言录音',
          action: 'delete',
          _id: 'customer_delete'
        }
      ],
      drawer: {
        title: '通话详情',
        show: false,
        callId: '',
        showSaveBtn: true
      },
      addForm: {
        createMethod: 'INSERT'
      },
      detailData: {},

      fieldListSearch: [], // 高级搜索字段
      isAdvanced: false, // 高级检索 普通搜索区分标识
      advancedObj: {}
    })

    const methods = reactive({
      getCallTypeText(type: string) {
        let label = '未知类型'
        switch (type) {
          case 'incoming':
            label = '呼入'
            break
          case 'dialout':
            label = '外呼'
            break
          case 'transfer':
            label = '呼叫转移'
            break
          case 'consultTransfer':
            label = '咨询转移'
            break
          case 'webcall':
            label = '双向回呼'
            break
          case 'previewDialout':
            label = '预览外呼'
            break
          case 'autoDialout':
            label = '自动外呼'
            break
        }
        return label
      },
      getHangUpSideName(hangUpSide: string) {
        if (hangUpSide === 'AGENT') {
          return '座席挂机'
        } else if (hangUpSide === 'CUSTOMER') {
          return '客户挂机'
        } else if (hangUpSide === 'SYSTEM') {
          return '系统挂机'
        }
      },
      getFailureReason(code: string) {
        let label
        switch (code) {
          case '-1':
            label = '未识别'
            break
          case '1':
            label = '禁止呼叫'
            break
          case '2':
            label = '服务不可用'
            break
          case '3':
            label = '请求终止'
            break
          case '4':
            label = '呼叫超时'
            break
          case '5':
            label = '正在通话'
            break
          case '6':
            label = '被叫未接听'
            break
          case '7':
            label = '被叫忙'
            break
          case '8':
            label = '空号'
            break
          case '9':
            label = '停机'
            break
          case '10':
            label = '关机'
            break
          case '11':
            label = '电话忙'
            break
          case '12':
            label = '呼叫等待'
            break
          case '13':
            label = '无法接通'
            break
          case '14':
            label = '无人接听'
            break
          case '15':
            label = '无法接听'
            break
          case '16':
            label = '稍后再拨'
            break
          case '17':
            label = '来电提醒'
            break
          case '18':
            label = '无权接受'
            break
          case '19':
            label = '不方便接听'
            break
          case '20':
            label = '不在服务区'
            break
          case '21':
            label = '前转不成功'
            break
          case '22':
            label = '不要挂机'
            break
          case '23':
            label = '呼入限制'
            break
          case '24':
            label = '暂停服务'
            break
          case '25':
            label = '没有应答'
            break
          case '26':
            label = '加拨零'
            break
          case '27':
            label = '外地号码'
            break
          case '28':
            label = '系统繁忙'
            break
          case '29':
            label = '网络忙'
            break
          case '30':
            label = '无子业务号码'
            break
          case '31':
            label = '无此业务号码'
            break
        }
        return label
      },
      getCallStatusName(status: any) {
        return (getCallStatusName as any)[status]
      },
      getTimeLength(timeLength: any) {
        return getCallTimeLength(timeLength, false)
      },
      getProvince(data: any) {
        let text = '未知'
        if (data.customerCountryCode === '86') {
          if (data.customerProvince) {
            text = data.customerProvince + '-' + data.customerCity
          }
        } else {
          if (data.customerCountry) {
            text = data.customerCountry
          }
        }
        return text
      }
    })

    const initSelectData = () => {
      const date = getCurrentDateTime().split(' ')[0]
      const lastDate = new Date(date + ' 00:00:00').getTime() - 7 * 24 * 60 * 60 * 1000
      const nextDate = new Date(date + ' 23:59:59').getTime()
      return [getFormatDateTime(new Date(lastDate), ''), getFormatDateTime(new Date(nextDate), '')]
    }

    const advancedState: any = reactive({
      fieldList: [
        {
          label: '客户号码',
          prop: 'customerNumber'
        },
        {
          label: '座席名称',
          prop: 'agentName'
        },
        {
          label: '呼叫类型',
          prop: 'callType'
        },
        {
          label: '呼叫状态',
          prop: 'status'
        },
        {
          label: '呼叫时间',
          prop: 'startTime'
        },
        {
          label: '通话时长', // 通话结束时间 - 呼叫时间
          prop: 'bridgeDuration'
        },
        {
          label: '通话录音',
          prop: 'recordFileUrl'
        },
        {
          label: '留言录音',
          prop: 'voiceMailUrl'
        },
        // 地区拆分成省市
        {
          label: '客户地区',
          prop: 'customerProvinceOrCity'
        },
        {
          label: '服务号',
          prop: 'trunkNumber'
        },
        {
          label: '外显号',
          prop: 'displayNumber'
        },
        {
          label: '外显号地区',
          prop: 'displayNumberArea'
        },
        {
          label: '虚拟号',
          prop: 'virtualNumber'
        },
        {
          label: '座席工号',
          prop: 'agentNumber'
        },
        // {
        //   label: '座席部门',
        //   prop: 'departments'
        // },
        {
          label: '转出座席工号',
          prop: 'transferAgent'
        },
        {
          label: '服务组',
          prop: 'queueName'
        },
        {
          label: '语音导航',
          prop: 'ivrId'
        },
        {
          label: '座席振铃时长', // 座席接听应答时间 - 呼叫时间
          prop: 'agentRingDuration'
        },
        {
          label: '座席接听时间', // 座席接听应答时间 - 呼叫时间
          prop: 'agentAnswerTime'
        },
        {
          label: '呼叫座席时间', // 座席接听应答时间 - 呼叫时间
          prop: 'agentStartTime'
        },
        {
          label: '客户振铃时长', // 客户接听应答时间 - 呼叫时间
          prop: 'customerRingDuration'
        },
        {
          label: '客户接听时间',
          prop: 'customerAnswerTime'
        },
        {
          label: '挂机方',
          prop: 'hangUpSide'
        },
        {
          label: '呼叫失败原因',
          prop: 'failureReason'
        },
        // {
        //   label: '满意度调查结果',
        //   prop: 'keys'
        // },
        {
          label: '满意度调查时长', // 满意度结束时间 - 满意度开始时间
          prop: 'satisfyDuration'
        },
        {
          label: '通话记录ID',
          prop: '_id'
        },
        {
          label: '客户名称',
          prop: 'customerName'
        },
        {
          label: '挂机时间',
          prop: 'hangupTime'
        }
        // {
        //   label: '标签',
        //   prop: 'tags'
        // }
      ],
      customList: [
        {
          name: '全部通话记录',
          default: true,
          advanceQuery: [[]]
        },
        {
          name: '我的通话记录',
          default: true,
          conditions: [
            [
              {
                fieldKey: 'agentNumber',
                fieldOperator: 'eq',
                fieldValue: [USERMODULE.agent.agentNumber || '200']
              },
              {
                fieldKey: 'startTime',
                fieldOperator: 'between',
                fieldValue: initSelectData()
              }
            ]
          ]
        }
      ],
      fieldSelectList: {
        status: [
          {
            _id: 'IVR',
            name: 'IVR'
          },
          {
            _id: 'QUEUE_ABANDON',
            name: '排队放弃'
          },
          {
            _id: 'ANSWER',
            name: '已接听'
          },
          {
            _id: 'AGENT_NO_ANSWER',
            name: '座席未接听'
          },
          {
            _id: 'CALL_LIMITE',
            name: '并发限制'
          },
          {
            _id: 'BLACK_LIST',
            name: '黑名单'
          },
          {
            _id: 'CUSTOMER_NO_ANSWER',
            name: '客户未接听'
          },
          {
            _id: 'CALL_TRANSFER',
            name: '呼叫转移'
          },
          {
            _id: 'CALL_CONSULT',
            name: '呼叫咨询'
          },
          {
            _id: 'CALL_CONSULT_TRANSFER',
            name: '咨询转移'
          },
          {
            _id: 'CALL_THREEWAY',
            name: '三方'
          },
          {
            _id: 'VOICEMAIL',
            name: '留言'
          },
          {
            _id: 'RISK',
            name: '风控拦截'
          }
        ],
        callType: [
          { name: '呼入', _id: 'incoming' },
          { name: '外呼', _id: 'dialout' },
          { name: '呼叫转移', _id: 'transfer' },
          { name: '咨询转移', _id: 'consultTransfer' },
          { name: '双向回呼', _id: 'webcall' },
          { name: '预览外呼', _id: 'previewDialout' },
          { name: '自动外呼', _id: 'autoDialout' }
        ],
        failureReason: [
          { name: '未识别', _id: '-1' },
          { name: '禁止呼叫', _id: '1' },
          { name: '服务不可用', _id: '2' },
          { name: '请求终止', _id: '3' },
          { name: '呼叫超时', _id: '4' },
          { name: '正在通话', _id: '5' },
          { name: '被叫未接听', _id: '6' },
          { name: '被叫忙', _id: '7' },
          { name: '空号', _id: '8' },
          { name: '停机', _id: '9' },
          { name: '关机', _id: '10' },
          { name: '电话忙', _id: '11' },
          { name: '呼叫等待', _id: '12' },
          { name: '无法接通', _id: '13' },
          { name: '无人接听', _id: '14' },
          { name: '无法接听', _id: '15' },
          { name: '稍后再拨', _id: '16' },
          { name: '来电提醒', _id: '17' },
          { name: '无权接受', _id: '18' },
          { name: '不方便接听', _id: '19' },
          { name: '不在服务区', _id: '20' },
          { name: '前转不成功', _id: '21' },
          { name: '不要挂机', _id: '22' },
          { name: '呼入限制', _id: '23' },
          { name: '暂停服务', _id: '24' },
          { name: '没有应答', _id: '25' },
          { name: '加拨零', _id: '26' },
          { name: '外地号码', _id: '27' },
          { name: '系统繁忙', _id: '28' },
          { name: '网络忙', _id: '29' },
          { name: '无子业务号码', _id: '30' },
          { name: '无此业务号码', _id: '31' }
        ],
        hangUpSide: [
          { name: '座席挂机', _id: 'AGENT' },
          { name: '客户挂机', _id: 'CUSTOMER' },
          { name: '系统挂机', _id: 'SYSTEM' }
        ],
        ivrId: [],
        customerCountry: [],
        displayNumberArea: [],
        tags: [],
        departments: []
      },
      conditionList: {
        // 等于  不等于 包含  不包含  为空      不为空     大于  大于等于 小于 小于等于 介于  不介于
        // 'eq', 'neq', 'in', 'nin', 'empty', 'nempty', 'gt', 'gte', 'lt', 'lte', 'btn', 'nbtn'
        // 客户号码
        customerNumber: { type: 'string', condition: ['eq'] },
        // 通话ID
        _id: { type: 'string', condition: ['eq'] },
        // 服务号
        trunkNumber: { type: 'string', condition: ['eq'] },
        // 外显号
        displayNumber: { type: 'string', condition: ['eq'] },
        // 虚拟号
        virtualNumber: { type: 'string', condition: ['eq'] },
        // 座席工号
        agentNumber: { type: 'string', condition: ['eq'] },
        // 坐席部门
        departments: {
          type: 'cascader',
          condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
          props: { value: '_id', label: 'name', children: 'children', multiple: true, emitPath: 'false' }
        },
        // 转出坐席工号
        transferAgent: { type: 'string', condition: ['eq'] },
        // 通话时长
        bridgeDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
        // 呼叫时间
        startTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
        // 满意度调查时长
        joinQeueTime: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
        // 座席应答时间
        agentAnswerTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
        // 座席振铃时长
        agentRingDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
        // 客户振铃时长
        customerRingDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
        // 满意度调查时长
        satisfyDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
        // 客户名称
        customerName: { type: 'string', condition: ['in', 'empty', 'nempty'] },
        // 呼叫类型
        callType: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 呼叫状态
        status: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 服务组名称
        queueName: { type: 'string', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 挂机方
        hangUpSide: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 座席名称
        agentName: { type: 'string', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 客户地区
        customerProvinceOrCity: {
          type: 'string',
          condition: ['eq', 'neq', 'empty', 'nempty'],
          props: { label: 'name', value: 'name' }
        },
        // 外显号地区
        displayNumberArea: {
          type: 'string',
          condition: ['eq', 'neq', 'empty', 'nempty'],
          props: { label: 'name', value: 'name' }
        },
        // 语音导航名称
        ivrId: {
          type: 'select',
          condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
          props: { label: 'name', value: 'nodeId' }
        },
        // 挂机时间
        hangupTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
        // 满意度调查
        // keys: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 客户接听时间
        customerAnswerTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
        // 呼叫座席时间
        agentStartTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
        // 呼叫失败原因
        failureReason: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
        // 通话录音
        recordFileUrl: { type: 'select', condition: ['empty', 'nempty'] },
        // 留言录音
        voiceMailUrl: { type: 'select', condition: ['empty', 'nempty'] }
        // // 标签
        // tags: {
        //   type: 'cascader',
        //   condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
        //   props: { value: '_id', label: 'name', children: 'children', multiple: true, emitPath: 'false' }
        // }
      },
      handleSearch(obj: any) {
        // 高级检索
        state.isAdvanced = true
        state.advancedObj = obj
        instance?.refs.customSearch.hidePopover()
        searchType(true)
      },
      saveConditionFun(obj: any) {
        //  高级搜索-保存常用检索
        saveOrUpdateQuickQuery({
          advanceQuery: obj.advanceQuery,
          name: obj.name,
          id: obj.currentCustomId
        }).then((res) => {
          if (res.success) {
            if (obj.currentCustomId) {
              // 更新
              advancedState.customList = advancedState.customList.map((item: any) => {
                if (item._id === obj.currentCustomId) {
                  item.name = obj.name
                  item.conditions = obj.advanceQuery
                  return item
                } else {
                  return item
                }
              })
              ElMessage.success('更新成功!')
            } else {
              advancedState.customList = advancedState.customList.concat({
                name: obj.name,
                conditions: obj.advanceQuery,
                _id: res.data.id
              })
              ElMessage.success('保存成功!')
            }
          }
        })
      }
    })

    const getConditionFun = () => {
      // 高级搜索-获取常用检索
      getQuickQuery({}).then((res) => {
        if (res.success) {
          if (res.data.list) {
            const transList = res.data.list.map((item: any) => {
              return {
                name: item.name,
                conditions: item.advanceQuery,
                _id: item.id
              }
            })
            advancedState.customList = advancedState.customList.concat(transList)
          }
        }
      })
    }

    const deleteCustomClick = (row: any) => {
      // 删除常用检索
      deleteQuickQuery({ id: row._id }).then((res) => {
        if (res.success) {
          advancedState.customList = advancedState.customList.filter((item: any) => {
            if (item._id !== row._id) {
              return true
            }
          })
          ElMessage.success('删除成功！')
        }
      })
    }

    const searchType = (init?: boolean) => {
      if (init) {
        state.pagingData.page = 1
      }
      if (state.isAdvanced) {
        // 高级搜索
        getList('advanced', state.advancedObj)
      } else {
        // 普通搜索
        getList('', {})
      }
    }

    const toDetail = async (row: any) => {
      // 详情
      state.drawer.show = true
      state.drawer.callId = row._id
    }

    const delCusFun = (row: any) => {
      ElMessageBox.confirm('删除后数据无法恢复，请确认是否删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      }).then(() => {
        delCus({ id: row._id }).then((res) => {
          if (res.success) {
            ElMessage.success('删除成功')
            searchFun()
          }
        })
      })
    }
    // 点击列表的听取录音，重置其他数据
    const restTablePlay = (data: any) => {
      const arr: any = []
      state.tableData.forEach((item: any) => {
        if (item._id === data._id) {
          item.isplay = data.isplay
        } else {
          item.isplay = false
        }
        arr.push(item)
      })
      state.tableData = arr
    }

    const checkHeadersChange = (checkList: any, init: boolean) => {
      if (init) {
        return
      }
      state.tableHeaders = checkList || []
      updateHeaderConfig()
    }

    // 批量操作
    const batchClick = (action: string, selectList: any) => {
      let ids = []
      let condition = {}
      if (selectList === true) {
        // 全选
        ids = []
        condition = { search: getParams(state.quickForm) }
      } else {
        // 部分选中
        ids = selectList
        condition = {}
      }
      switch (action) {
        case 'distribute':
          batchDistrubute(ids, condition)
          break
        case 'delete':
          batchDelete(ids, condition)
          break
      }
    }

    // 批量分配
    const batchDistrubute = (ids: [], condition: any) => {
      ElMessageBox.confirm('确定要批量导出记录吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await nextTick()
        instance?.refs.distributeCustomer.openDialog(ids, condition, true)
      })
    }

    // 批量删除
    const batchDelete = (ids: any = [], condition = {}) => {
      ElMessageBox.confirm('确定要批量删除客户吗', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      }).then(() => {
        batchDel({
          ids,
          condition
        }).then((res) => {
          if (res.success) {
            ElMessage.success('操作成功')
            clearBatchSelect()
          }
        })
      })
    }

    // 清空操作栏
    const clearBatchSelect = () => {
      instance?.refs.tableRef.cancelSelectFun()
      searchFun()
    }

    const handleCurrentChange = (page: number) => {
      state.pagingData.page = page
      searchType()
    }

    const handleSizeChange = (size: number) => {
      state.pagingData.limit = size
      searchType(true)
    }

    // 搜索
    const searchFun = () => {
      state.isAdvanced = false
      state.pagingData.page = 1
      searchType(true)
    }

    const closeDraw = () => {
      state.drawer.show = false // 关闭抽屉
    }

    // 处理参数
    const getParams = (form: any) => {
      const arr: any = [] // 存储
      const arr2 = Object.keys(form) // state.form对应的数组
      if (arr2 && arr2.length) {
        arr2.forEach((item) => {
          if (state.quickForm[item]) {
            arr.push({
              field: item,
              value: [state.quickForm[item]],
              operator: 'eq'
            })
          }
        })
      }
      return arr
    }
    const handleQuickForm = () => {
      const quickForm: any = state.quickForm
      console.log(quickForm, 'lkllllllllllllllllls')
      const query: any = {}
      if (quickForm) {
        Object.keys(quickForm).forEach((key) => {
          if (key === 'startTime') {
            if (quickForm[key] && quickForm[key].length > 0) {
              query.startTime1 = quickForm[key][0]
              query.startTime2 = quickForm[key][1]
            }
          } else {
            if (quickForm[key] && quickForm[key].length > 0) {
              query[key] = quickForm[key]
            }
          }
        })
      }
      return query
    }
    // 获取字段
    const getList = (type?: string, obj?: any) => {
      state.loading = true
      let sendData: any = {
        pageSize: state.pagingData.limit,
        pageNumber: state.pagingData.page
      }
      if (type) {
        sendData.advanceQuery = obj.advanceQuery || []
        sendData.id = obj.id || ''
      } else {
        const query = handleQuickForm() || {}
        sendData = { ...sendData, ...query }
      }

      getCdrList(sendData)
        .then((res: any) => {
          if (res.success && res.data) {
            bus.emit('restAudioStatus') // 查询的时候重置播放按钮
            state.tableData = res.data.list || []
            state.pagingData.total = res.data.page.total
          }
          state.loading = false
        })
        .catch(() => {
          state.loading = false
        })
    }
    // 获取满意度的配置
    const getSatisfaction = () => {
      getData({ accountId: USERMODULE.accountId || '' }).then((res) => {
        if (res && res.success && res.data) {
          state.satisfactionData = res.data || {}
        }
      })
    }

    // 获取表头
    const getHeaderConfig = () => {
      getCdrHeader({}).then((res) => {
        if (res.success && res.data) {
          const headers = res.data.config || []
          headers.push({ label: '操作', prop: 'oprate', show: true })
          state.tableHeaders = handleHeadersData(headers)
        }
      })
    }
    const handleHeadersData = (headers: any) => {
      const arr = [
        'callType',
        'recordFileUrl',
        'voiceMailUrl',
        'bridgeDuration',
        'customerCountry',
        'displayNumberArea',
        'agentRingDuration',
        'customerRingDuration',
        'hangUpSide',
        'keys',
        'status',
        'satisfyDuration',
        'failureReason'
      ]
      headers.forEach((item: any) => {
        if (arr.includes(item.prop)) {
          item.custom = true
        }
      })
      return headers
    }

    // 更新表头
    const updateHeaderConfig = () => {
      const headers = deepClone(state.tableHeaders)
      headers.splice(headers.length - 1, 1) // 去掉操作
      setCdrHeader({ config: headers }) // 更新表头数据
    }

    const setQuickStartTime = () => {
      state.quickForm.startTime = initSelectData()
    }

    onMounted(async () => {
      await mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段
      await mcCache.$getCache('cusInfo', 'hasObj', '', '', '', '', 'field') // 客户信息
      await mcCache.$getCache('region') // 地区
      mcCache.$getCache('ivrNav').then((data: any) => {
        advancedState.fieldSelectList.ivrId = data
      })
      await getHeaderConfig() // 表头
      getSatisfaction() // 获取满意度配置
      setQuickStartTime() // 初始化时间区间
      getList() // 列表
      getConditionFun()
    })

    return {
      ...toRefs(state),
      ...toRefs(methods),
      ...toRefs(advancedState),
      closeDraw,
      searchFun,
      handleSizeChange,
      handleCurrentChange,
      clearBatchSelect,
      batchClick,
      checkHeadersChange,
      delCusFun,
      toDetail,
      customSearch,
      restTablePlay,
      searchType,
      deleteCustomClick
    }
  }
})
</script>

<style lang="stylus" scoped>
.call-record
  width 100%
.customer-pool
  padding 24px
  .btn
    color var(--mc-main-color)
    cursor pointer
    margin-right 16px
    &:last-child
      margin-right 0px
.record-audio
  a
    text-decoration: none;
  .MC_icon-shangchuan-xiazai
    font-size 20px
    color var(--mc-main-color)
    margin-left 18px
</style>
